var help = "You should fill the forms and put CITY1 or CITY1 in data fields, it will replace by the item in each sort of data. Please split each city with ENTER";
var city1_not_found = "City1 not found! Please put it somewhere on form";
var city2_not_found = "City2 not found! Please put it somewhere on form";
var form_not_found = "Something is not right! we can not find the target form!";

// Just for CSS
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');


    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle(
    ".attack { text-align: center; background: red; margin: 2em; border-radius: 3em; padding: 1em } " +

    "input[type=button] { padding: 1em } "
);

function stopPost() {
    $(this).attr('value', 'Start').unbind('click').click(startPost);
}

function startPost() {

    var self = $(this);
    var parent = self.parent();
    var form = $('form[name=form]');
    
    var list1 = $('textarea:eq(0)', parent);
    var list2 = $('textarea:eq(1)', parent);

    var interval = $('select', parent);

    if($(list1).val().length == 0) {
        alert("You should enter at least 1 city for list 1");
        return;
    }
    
    if($(list2).val().length == 0) {

        alert("You should enter at least 1 city for list 2");
        return;
    }
    

    var lines1 = $(list1).val().split('\n');
    var lines2 = $(list2).val().split('\n');

    var query = form.serializeArray();
    for(var i = 0; i < query.length; i++) {
        if(query[i].name == "title") {
            if(query[i].value.indexOf('CITY1') == -1) {
                alert(city1_not_found);
                return;
            }
            if(query[i].value.indexOf('CITY2') == -1) {
                alert(city2_not_found);
                return;
            }
        }
    }

    var l = $(log).text('Start...\n');
    
    var items = [];
    var index = 0;
    
    $.each(lines1, function(index1, line1){
        $.each(lines2, function(index2, line2){
            for(var i = 0; i < query.length; i++) {
                query[i].value = query[i].value.replace("CITY1", line1).replace("CITY2", line2);
            }
    
            var queryString = "";
            for(var i = 0; i < query.length; i++) {
                //if(query[i].name == "title" && query[i].name == "content") {
			        //alert(query[i].value);
                    queryString += "&" + query[i].name + "=" + encodeToGb2312(query[i].value);
                //}
            }

            
            //var text = query.replace("CITY1", line1).replace("CITY2", line2);
            if(line1.length > 0 && line2.length > 0) {
                items.push({"query": queryString.substring(1), "comment": line1 + " > " + line2});

                index = 0;
            }
        });
    });
    
    var action = form.attr('action');
    var method = form.attr('method');

    
    
    var intervalId = setInterval(function() {
        $.ajax({
                type: "post",
                url: "send_product_pro.asp",
                data: items[index].query,
                contentType: "application/x-www-form-urlencoded",

                dataType: 'text'})
                    .done(function() {
                        l.text(l.text() + "Sent: " + items[index].comment + "\n");
                    })
                    .fail(function(xhr, status, error) {

                        //var err = eval("(" + xhr.responseText + ")");
                    //    alert(xhr.status);
                    //    alert(xhr.responseText);
                    }).always(function() {

                        index++;
                        
                        if(items.length <= index) {
                            clearInterval(intervalId);
                            stopPost.call(self);

                        }
                    });
    }, Number(interval.val()));
    
    self.attr('value', 'Stop').unbind('click').click(function() {
        l.text(l.text() + "Stopped");

        clearInterval(intervalId);
        stopPost.call(self);
    });
}

var form = $('form[name=form]');
if(form.length == 1) {    
    // generate contents    
    var div = $('<div class="attack"></div>');
    
    $('<p></p>').text(help).appendTo(div);


    var list1 = $('<textarea placeholder="List for city1" rows="4" cols="30"></textarea>').appendTo(div);
    var list2 = $('<textarea placeholder="List for city2" rows="4" cols="30"></textarea>').appendTo(div);


    var start = $('<input type="button" value="Start!" />').appendTo(div.append('<br/>'));
    var interval = $("<select>" +
        "<option value='10000'>10 sec</option>" + 

        "<option value='30000'>30 sec</option>" + 
        "<option value='60000'>1 min</option>" + 
        "<option value='120000'>2 min</option>" +

        "</select>").appendTo(div);
    var log = $('<pre></pre>').appendTo(div);

    $(document.body).prepend(div);
    
    // startPost
    start.click(startPost);


} else {
    alert(form_not_found);
}
